package com.thkj.interceptor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.thkj.service.RequestLogService;

@Aspect
@Component
public class PermissionsAspect {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	RequestLogService requestLogService;

	ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

	@Pointcut("@annotation(com.thkj.interceptor.Permissions)")
	public void pointcut() {
	}

	@Before("pointcut()")
	public void doBefore(JoinPoint joinPoint) {
		String permissions = this.getPermissions(joinPoint);
//        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		// 验证是否有权限执行方法
	}

	@After("pointcut()")
	public void doAfter(JoinPoint joinPoint) {
//		HttpServletRequest request = SpringUtil.getRequest();
//		RmLoginUserInfo loginUser = RmUtil.getLoginUser(request);
//		RequestLog requestLog = new RequestLog();
//		requestLog.setCreateTime(DateUtil.getNowAsTimestamp());
//		requestLog.setId(UUIDUtil.randomUUID());
//		requestLog.setIp(ServletUtil.getClientIP(request));
//		requestLog.setOperatorId(loginUser.getPersonuuid());
//		requestLog.setOperatorName(loginUser.getUserName());
//		requestLog.setRequestParam(getParamString(request.getParameterMap()));
//		requestLog.setRequestUri(request.getServletPath());
//		requestLog.setType("1");
//		cachedThreadPool.execute(new Runnable() {
//			@Override
//			public void run() {
//				requestLogService.insert(requestLog);
//			}
//		});
	}

	/**
	 * 取注解上的授权代码
	 * 
	 * @param point
	 * @return
	 */
	private String getPermissions(JoinPoint point) {
		Method method = ((MethodSignature) point.getSignature()).getMethod();
		Permissions annotation = method.getAnnotation(Permissions.class);
		return annotation.value();
	}

	private String getParamString(Map<String, String[]> map) {
		StringBuilder sb = new StringBuilder();
		int count = 1;
		for (Map.Entry<String, String[]> e : map.entrySet()) {
			sb.append(e.getKey()).append("=");
			String[] value = e.getValue();
			if (value != null && value.length == 1) {
				sb.append(value[0]);
			} else {
				sb.append(Arrays.toString(value));
			}
			if (count < map.size()) {
				sb.append("&");
			}
			count++;
		}
		return sb.toString();
	}
}
